package org.app4j.passport.service;

import java.util.Date;

import org.app4j.passport.domain.User;

/**
 * @author Chi
 */
public class UserTokenParser {

  public UserTokenParser() {}

  public String toToken(User user, Date timestamp) {
    StringBuilder b = new StringBuilder();
    b.append(user.getId());
    b.append("-");
    b.append(timestamp.getTime());
    b.append("-");
    b.append(user.getUsername());
    b.append("-");

    b.append(user.getRoles());

    return b.toString();
  }

  public User fromToken(String token) {
    try {
      User user = new User();
      StringBuilder b = new StringBuilder();
      int state = 0;

      for (int i = 0; i < token.length(); i++) {
        char c = token.charAt(i);
        if (c == '-' && state == 0) {
          user.setId(Long.valueOf(b.toString()));
          b.delete(0, b.length());
          state++;
        } else if (c == '-' && state == 1) {
          long timestamp = Long.valueOf(b.toString());
          user.setCreateTime(new Date(timestamp));
          b.delete(0, b.length());
          state++;
        } else if (c == '-' && state == 2) {
          user.setUsername(b.toString());
          b.delete(0, b.length());
          state++;
        } else {
          b.append(c);
        }
      }

      user.setRoles(b.toString());
      return user;
    } catch (Exception e) {
      return null;
    }
  }
}
